package pushup.view.providers;


import java.util.HashMap;

import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import pushup.model.Field;
import pushup.model.Statistics;
import pushup.model.Type;

public class ViewLabelProvider extends LabelProvider implements ITableLabelProvider, ITableColorProvider {
	
	private Statistics statistics;
	
	public ViewLabelProvider(Statistics statistics){
		super();
		this.statistics = statistics;
	}
	
	public String getColumnText(Object obj, int index) {
		Type type = ((Type) obj);
		switch(index){
		case 0 : {
			return type.getName();
		}
		
		case 1 : {
			return type.getNumberOfSimilarClasses() + "";
		}
		
		case 2 : {
			return type.getMaxSimilarities() + "";
		}
		
		case 3 : {
			return type.getBestCandidate().getName();
		}
		
		case 4 : {
			StringBuffer buffer = new StringBuffer();
			HashMap<Type, Integer> occurrences = new HashMap<Type, Integer>();
			
			for(Field field : type.getSimilarities().get(type.getBestCandidate())){
				if(!occurrences.containsKey(field.getFieldType())){
					occurrences.put(field.getFieldType(), 1);
				} else {
					occurrences.put(field.getFieldType(), occurrences.get(field.getFieldType()) + 1);
				}
				
			}
			
			for(Type fieldType : occurrences.keySet()){
				buffer.append("[");
				buffer.append(occurrences.get(fieldType));
				buffer.append("] ");
				buffer.append(fieldType.getShortName());
				buffer.append(" ");
			}
			
			return buffer.toString();
		}
		
		default : return "N/A";
		}
		
	}
	
	public Image getColumnImage(Object obj, int index) {
		if(index == 0 || index == 3){
			return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
		}
		
		return null;
	}

	public Color getForeground(Object element, int columnIndex) {
		return null;
	}

	public Color getBackground(Object element, int columnIndex) {
		Type type = ((Type) element);
		
		//java.awt.Color color1 = new java.awt.Color(152,251,152);
		java.awt.Color color1 = new java.awt.Color(255,255,255);
		java.awt.Color color2 = new java.awt.Color(255,64,64);
        
        float ratio =  (float)type.getMaxSimilarities() / (float)statistics.getMaxSimilarity();
		
		int red = (int) (color2.getRed() * ratio + color1.getRed() * (1 - ratio));
        int green = (int) (color2.getGreen() * ratio + color1.getGreen() * (1 - ratio));
        int blue = (int) (color2.getBlue() * ratio + color1.getBlue() * (1 - ratio));
        
		return new Color(null, red, green, blue);
	}
	
}
